const express = require('express')
const router = express.Router()
const fs = require('fs')
const path = require('path')

router.get('/coverPicture', (req, res, next) => {
  try {
    const imgName = req.query.img
    const realFilePath = path.resolve(
      __dirname,
      `./../public/cover_picture/${imgName}`
    )
    console.log(realFilePath)
    const fakeFilePath = path.resolve(
      __dirname,
      `./../public/cover_picture/404.png`
    )
    let filePath = ''
    if (fs.existsSync(realFilePath)) {
      filePath = realFilePath
    } else {
      filePath = fakeFilePath
    }
    // 给客户端返回一个文件流
    // 格式必须为 binary，否则会出错
    // 创建文件可读流
    const cs = fs.createReadStream(filePath)
    cs.on('data', (chunk) => {
      res.write(chunk)
    })
    cs.on('end', () => {
      res.status(200)
      res.end()
    })
  } catch (err) {
    console.log(err)
  }
})

router.get('/avatar', (req, res, next) => {
  try {
    const imgName = req.query.img
    const realFilePath = path.resolve(
      __dirname,
      `./../public/avatar/${imgName}`
    )
    const fakeFilePath = path.resolve(__dirname, `./../public/avatar/404.gif`)
    let filePath = ''
    if (fs.existsSync(realFilePath)) {
      filePath = realFilePath
    } else {
      filePath = fakeFilePath
    }
    // 给客户端返回一个文件流
    // 格式必须为 binary，否则会出错
    // 创建文件可读流
    const cs = fs.createReadStream(filePath)
    cs.on('data', (chunk) => {
      res.write(chunk)
    })
    cs.on('end', () => {
      res.status(200)
      res.end()
    })
  } catch (err) {
    console.log(err)
  }
})
module.exports = router
